package com.ecut.drug_bid.controller;

import com.ecut.drug_bid.domain.Message;
import com.ecut.drug_bid.dto.MessageCreateRequest;
import com.ecut.drug_bid.service.MessageService;
import com.ecut.drug_bid.util.UserContext;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/messages")
@RequiredArgsConstructor
public class MessageController {
    private final MessageService messageService;

    // 查询所有已发布的留言
    @GetMapping
    public ResponseEntity<List<Message>> list(
        @RequestParam(required = false) String tenderCode,
        @RequestParam(required = false) Long authorId
    ) {
        if (tenderCode != null) {
            return ResponseEntity.ok(messageService.findByTenderCode(tenderCode));
        }
        if (authorId != null) {
            return ResponseEntity.ok(messageService.findByAuthorId(authorId));
        }
        return ResponseEntity.ok(messageService.findAllPublished());
    }

    // 根据ID查询
    @GetMapping("/{id}")
    public ResponseEntity<Message> getById(@PathVariable(name = "id") Long id) {
        return messageService.findById(id)
            .map(ResponseEntity::ok)
            .orElseGet(() -> ResponseEntity.notFound().build());
    }

    // 发布留言（需要登录）
    @PostMapping
    public ResponseEntity<Message> create(@Valid @RequestBody MessageCreateRequest request) {
        Long userId = UserContext.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.status(401).build();
        }
        Message message = messageService.create(request, userId);
        return ResponseEntity.ok(message);
    }

    // 隐藏留言（仅管理员）
    @PutMapping("/{id}/hide")
    public ResponseEntity<Map<String, String>> hide(@PathVariable(name = "id") Long id) {
        String userType = UserContext.getCurrentUserType();
        if (!"ADMIN".equals(userType)) {
            return ResponseEntity.status(403).build();
        }
        messageService.hide(id);
        Map<String, String> response = new HashMap<>();
        response.put("message", "留言已隐藏");
        return ResponseEntity.ok(response);
    }

    // 删除留言（管理员或作者本人）
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable(name = "id") Long id) {
        Long userId = UserContext.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.status(401).build();
        }
        messageService.delete(id);
        return ResponseEntity.noContent().build();
    }
}